package logx

import (
	"fmt"
	"os"
	"sync"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

var (
	Logger  *zap.Logger
	onceLog sync.Once
)

func Init() error {
	var initErr error
	onceLog.Do(func() {

		logDir := "./logs"
		err := os.MkdirAll(logDir, 0755)

		if err != nil {
			initErr = fmt.Errorf("创建日志目录失败: %v", err)
			return
		}

		infoFile := logDir + "/info.log"
		errorFile := logDir + "/error.log"

		infoWriter := getWriter(infoFile)
		errorWriter := getWriter(errorFile)

		encoderConfig := zapcore.EncoderConfig{
			TimeKey:       "time",
			LevelKey:      "level",
			NameKey:       "logger",
			CallerKey:     "caller",
			MessageKey:    "msg",
			StacktraceKey: "stacktrace",
			LineEnding:    zapcore.DefaultLineEnding,
			EncodeLevel:   zapcore.CapitalColorLevelEncoder,
			EncodeTime:    zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000"),
			EncodeCaller:  zapcore.ShortCallerEncoder,
		}

		infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
			return lvl >= zapcore.InfoLevel && lvl < zapcore.ErrorLevel
		})
		errorLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
			return lvl >= zapcore.ErrorLevel
		})

		infoCore := zapcore.NewCore(
			zapcore.NewConsoleEncoder(encoderConfig),
			zapcore.AddSync(infoWriter),
			infoLevel,
		)
		errorCore := zapcore.NewCore(
			zapcore.NewConsoleEncoder(encoderConfig),
			zapcore.AddSync(errorWriter),
			errorLevel,
		)

		// consoleCore := zapcore.NewCore(
		// 	zapcore.NewConsoleEncoder(encoderConfig),
		// 	zapcore.AddSync(os.Stdout),
		// 	zapcore.DebugLevel, // 控制台输出所有级别
		// )

		core := zapcore.NewTee(infoCore, errorCore /*, consoleCore*/)

		Logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))

		Logger.Info("日志系统初始化完成", zap.String("info_file", infoFile), zap.String("error_file", errorFile))

	})

	if initErr != nil {
		return initErr
	}

	return nil
}

func getWriter(filename string) zapcore.WriteSyncer {
	return zapcore.AddSync(&lumberjack.Logger{
		Filename:   filename,
		MaxSize:    20,   // 单个日志最大20MB
		MaxBackups: 10,   // 最多保留10个旧文件
		MaxAge:     7,    // 日志保留7天
		Compress:   true, // 启用压缩
	})
}
